package cn.com.bluemoon.daps.model.core.file.excel.converter;

import cn.com.bluemoon.daps.common.constant.DapConstant;
import cn.com.bluemoon.daps.model.core.cache.ModelCacheHelper;
import cn.com.bluemoon.daps.standard.entity.DapSystemCategory;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.converters.string.StringStringConverter;
import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * 自定义string转为boolean
 *
 * @author Jarod.Kong
 * @date 2021/2/7 15:54
 */
@Slf4j
public class MyTopicCategoryStringStringConverter extends StringStringConverter {
    public static final String TOPIC_SPLIT_CHAR = "/";
    public static final String TOPIC_ID_DB_SPLIT_CHAR = ",";
    private final List<DapSystemCategory> topic2s;
    private final List<DapSystemCategory> categories1;

    public MyTopicCategoryStringStringConverter() {
        // 初始化一次
        Map<String, List<DapSystemCategory>> topicAndCategories = ModelCacheHelper.getTopicAndCategoriesByCache();
        topic2s = topicAndCategories.get(DapConstant.DapStandard.SYSTEM_TOPIC2_NAME);
        categories1 = topicAndCategories.get(DapConstant.DapStandard.SYSTEM_CATEGORY1_NAME);
    }

    @Override
    public String convertToJavaData(CellData cellData, ExcelContentProperty property, GlobalConfiguration config) {
        final String topics = cellData.getStringValue();
        if (StringUtils.isBlank(topics)) {
            log.error("主题列为必填项");
            return null;
        }
        final String[] topicsArr = topics.split(TOPIC_SPLIT_CHAR);
        if (topicsArr.length < 2) {
            log.error("主题分类，至少指定主题和一级分类");
            return null;
        }
        final String topic = StrUtil.trim(topicsArr[0]);
        final String category1 = StrUtil.trim(topicsArr[1]);
//        final String category2 = (topicsArr.length == 3) ? StrUtil.trim(topicsArr[2]) : "";
//        final String category3 = (topicsArr.length == 4) ? StrUtil.trim(topicsArr[3]) : "";
        List<String> topicIds = new ArrayList<>(topicsArr.length);
        Optional<DapSystemCategory> topicObj = topic2s.stream()
                .filter(o -> o.getCodeName().equalsIgnoreCase(topic)).findAny();
        if (!topicObj.isPresent()) {
            log.error("主题分类，列值与系统主题匹配失败");
            return null;
        }
        String topicId = topicObj.get().getId();
        topicIds.add(topicId);
        Optional<DapSystemCategory> category1Obj = categories1.stream()
                .filter(o -> o.getParentId().equals(topicId))
                .filter(o -> o.getCodeName().equalsIgnoreCase(category1)).findFirst();
        if (!category1Obj.isPresent()) {
            log.error("主题分类，列值与系统一级分类匹配失败");
            return null;
        }
        String category1Id = category1Obj.get().getId();
        topicIds.add(category1Id);
        log.debug("校验通过，翻译到的主题[{}]=[{}]", topics, String.join(TOPIC_SPLIT_CHAR, topicIds));
        return String.join(TOPIC_ID_DB_SPLIT_CHAR, topicIds);
    }

    @Override
    public CellData convertToExcelData(String value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) {
        if (StringUtils.isBlank(value)) {
            return super.convertToExcelData(value, contentProperty, globalConfiguration);
        }
        String[] topicIds = value.split(TOPIC_ID_DB_SPLIT_CHAR);
        if (topicIds.length == 0) {
            return super.convertToExcelData(value, contentProperty, globalConfiguration);
        }
        if (topicIds.length < 2) {
            log.error("主题分类，至少指定主题和一级分类");
            return new CellData("");
        }
        // action
        List<String> topicNames = Lists.newArrayList();
        String topic2Id = topicIds[0];
        String category1Id = topicIds[1];
        Optional<DapSystemCategory> topicOpt = topic2s.stream()
                .filter(o -> o.getId().equals(topic2Id)).findFirst();
        topicOpt.ifPresent(t -> {
            topicNames.add(t.getCodeName());
            Optional<DapSystemCategory> c1Opt = categories1.stream()
                    .filter(o -> o.getParentId().equals(topic2Id))
                    .filter(o -> o.getId().equals(category1Id)).findFirst();
            c1Opt.ifPresent(c -> {
                topicNames.add(c.getCodeName());
                if (topicIds.length == 3) {
                    String category2Id = topicIds[2];
                    List<DapSystemCategory> nextNodes = c.getNextNodes();
                    Optional<DapSystemCategory> c2Opt = nextNodes.stream().filter(c2 -> c2.getId().equals(category2Id)).findFirst();
                    c2Opt.ifPresent(c2 -> {
                        topicNames.add(c2.getCodeName());
                    });
                }
            });
        });
        String nameStr = String.join(TOPIC_SPLIT_CHAR, topicNames);
        return new CellData(nameStr);
    }
}